import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		openId:'',
		token:'',
		cartNum:0,
		hasLogin: false,
		loginTime:null,
		userInfo: {},
		marketId:1,
		h5url:"http://ccmc.cainiulife.com/#",
		CategoryList:[],
		Station:{},
		pushMessage: {}
	},
	mutations: {
		updatePushMessage(state, message) {
			/**
			 * 注意：这里为了方便预览查看效果，始终对 payload 做了序列化的处理。
			 * 实际开发期中，请自行调整代码并注意发送的 payload 消息格式。
			 */
			let payload = message.payload;
			if (typeof payload !== 'string') {
				message.payload = JSON.stringify(payload);
			}
			state.pushMessage = message || {};
		},
		setOpenid(state,provider){
			state.openId = provider;
			uni.setStorage({//缓存用户登陆状态
			    key: 'openId',
			    data: provider
			})
		},
		setStation(state,provider){
			state.Station = provider;
			uni.setStorage({//缓存用户登陆状态
			    key: 'Station',
			    data: provider
			})
		},
		setCategoryList(state,provider){
			state.CategoryList = provider;
			uni.setStorage({//缓存用户登陆状态
			    key: 'CategoryList',
			    data: provider
			})
		},
		showCartNum(state){
			//uni.setStorageSync("cartNum",null)
			var num =uni.getStorageSync("cartNum");
			if(!num)
			{
				num=0;
			}
			state.cartNum=num;
			if(state.cartNum<1)
			{
				uni.removeTabBarBadge({
					index:2
				})
			}
			else
			{

				uni.setTabBarBadge({
					index:2,
					text: state.cartNum + ""
				});
			}
		},
		setCartNum(state,cartNum){
			state.cartNum =parseInt(state.cartNum)+parseInt(cartNum)
			if(state.cartNum<1)
			{
				uni.removeTabBarBadge({
					index:2
				})
			}
			else
			{
				uni.setTabBarBadge({
					index:2,
					text: state.cartNum + ""
				});
			}
			uni.setStorageSync("cartNum",state.cartNum)
		},
		cartCartNum(state,cartNum){
			state.cartNum =parseInt(cartNum)
			if(state.cartNum<1)
			{
				uni.removeTabBarBadge({
					index:2
				})
			}
			else
			{
				uni.setTabBarBadge({
					index:2,
					text: state.cartNum + ""
				});
			}
			uni.setStorageSync("cartNum",state.cartNum)
		},
		getUserInfo(state) {
			uni.getStorage({
              key: 'userInfo',
               success: function (res) {
                   console.log('res data 异步获取 = ' + res.data);
				   state.userInfo = res.data;
				}
			});
		},
		saveUserInfo(state, provider,token) {
			state.hasLogin = true;
			state.userInfo = provider;
			state.token = token;
			state.loginTime = new Date();
			uni.setStorage({//缓存用户登陆状态
			    key: 'userInfo',
			    data: provider
			})
		},
		setUserToken(state,token){
			state.token = token
			uni.setStorage({//缓存用户登陆状态
				key: 'token',
				data: token
			})
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			state.token = '';
			state.Station={}
			state.loginTime = null;
			uni.removeStorage({
                key: 'userInfo'
            })
			uni.removeStorage({
			    key: 'token'
			})
		}
	},
	actions: {

	}
})

export default store
